//
//  HWRankListView.swift
//  HWanGame
//
//  Created by Apple on 2024/8/10.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import Stevia

//MARK: 榜单分类topView
class HWRankListTopView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var sourceData: [HWHomeNormalGameTypeModel]? {
        didSet{
            collectionView.reloadData()
        }
    }
    var updateCateData: ((_ cateID: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .clear
        
        addSubview(collectionView)
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.scrollDirection = .horizontal
//        layout.itemSize = CGSize(width: 45*widthScale, height: 38*widthScale)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12*widthScale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWWuKongCateCell.self, forCellWithReuseIdentifier: HWWuKongCateCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return sourceData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HWWuKongCateCell.description(), for: indexPath) as? HWWuKongCateCell else { return UICollectionViewCell() }
        cell.gameModel = sourceData?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [HWHomeNormalGameTypeModel]()
        sourceData?.forEach { model in
            let itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        sourceData = models
        updateCateData?(models[indexPath.row].id)
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let name = sourceData?[indexPath.row].name ?? ""
        let font = 14.font_medium
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width
        
        return CGSize(width: width, height: 38.0*widthScale)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 榜单列表
class HWRankCell: UITableViewCell {
    
    private let rankImageV = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let iconImageV = c_make_ex(UIImageView.self)
        .corner(12*widthScale).mode(.scaleAspectFill).end()
    private let shadowView = c_make_ex(UIView.self)
        .corner(12*widthScale).bgColor("#000000".toColor.alpha(0.1)).end()
    private let bgView = c_make_ex(UIView.self)
        .bgColor("#F2F3F5").corner(8*widthScale, corners: [.layerMinXMinYCorner,.layerMinXMaxYCorner]).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(14.font_semiBold).end()
    private let tagLabel = c_make_ex(UILabel.self)
        .color(UIColor.color(hexString: "#E55C67", alpha: 0.6)).font(8.font_medium)
        .corner(4*widthScale).color("#E55C67").end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(13.font_semiBold).end()
    private let scoreLabel = UIIconButton(style: .leading(itemSpace: 2))
    private let infoButton =  c_make_ex(UIButton.self)
        .color(.black).font(14.font_semiBold).text("详情")
        .corner(15*widthScale).text("已预约",state: .selected)
        .color("#AEB0B3",state: .selected).end()
    private let rankLabel =  c_make_ex(UILabel.self)
        .color("#AEB0B3").font(12.font_wide).alignment(.center).end()
    private let bgViewColor = ["#CC5266","#E5822E","#6BB2B2"]

    var yuyueGameBlock: ((_ gameId: String) -> Void)?
    
    var model: HWHomeGameModel? {
        didSet{
            guard let md = model else { return }
            
            iconImageV.sd_setImage(with: URL(string: md.icon))
            nameLabel.text = md.name
            let tagStr = md.biaoqian.joined(separator: " · ")
            subLabel.text = tagStr
            if md.pay.count > 0 {
                tagLabel.isHidden = false
                tagLabel.text = " " + md.pay
            }else{
                tagLabel.isHidden = true
            }
            if md.sort < 3 {
                rankImageV.isHidden = false
                rankLabel.isHidden = true
                rankImageV.image = "HomeRank_\(md.sort)".toImage
                scoreLabel.setImage("ScoreStar_white".toImage, for: .normal)
                scoreLabel.setTitleColor(.white, for: .normal)
                infoButton.layer.borderColor = UIColor.white.cgColor
                infoButton.setTitleColor(.white, for: .normal)
                bgView.backgroundColor = bgViewColor[md.sort].toColor
                tagLabel.backgroundColor = .white.alpha(0.2)
                tagLabel.textColor = .white
                subLabel.textColor = .white.alpha(0.92)
                nameLabel.textColor = .white
            }else{
                rankImageV.isHidden = true
                rankLabel.isHidden = false
                rankLabel.text = String(format: "%02d", md.sort)
                scoreLabel.setImage("ScoreStar_gray".toImage, for: .normal)
                scoreLabel.setTitleColor("#666666".toColor, for: .normal)
                infoButton.layer.borderColor = "#2E3033".toColor.cgColor
                infoButton.setTitleColor("#2E3033".toColor, for: .normal)
                bgView.backgroundColor = "#F2F3F5".toColor
                tagLabel.backgroundColor = "#E55C67".toColor.alpha(0.1)
                tagLabel.textColor = "#E55C67".toColor
                subLabel.textColor = "#AEB0B3".toColor
                nameLabel.textColor = .black
            }
            
            if md.is_yuyue == 1 {
                infoButton.layer.borderColor = "AEB0B3".toColor.cgColor
                infoButton.isSelected = true
            }
            
            scoreLabel.setTitle("\(md.point)", for: .normal)
        }
    }
    
    var gameType = "" {
        didSet{
            if gameType == "4"{
                infoButton.isUserInteractionEnabled = true
                infoButton.setTitle("预约", for: .normal)
            }else{
                infoButton.isUserInteractionEnabled = false
                infoButton.setTitle("详情", for: .normal)
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            rankImageV
            iconImageV
            shadowView
            rankLabel
            bgView.subviews{
                nameLabel
                tagLabel
                subLabel
                scoreLabel
                infoButton
            }
        }
        
        scoreLabel.style { v in
            v.iconSize = CGSize(width: 14*widthScale, height: 14*widthScale)
            v.setImage("ScoreStar_white".toImage, for: .normal)
            v.setTitleColor("#FF7500".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        infoButton.layer.borderWidth = 1.5*widthScale
        
        bgView.trailing(0).top(3*widthScale).bottom(13*widthScale).height(74*widthScale)
        rankImageV.leading(12*widthScale).size(32*widthScale)
        iconImageV.leading(48*widthScale).size(60*widthScale)
        shadowView.leading(48*widthScale).size(60*widthScale)
        rankLabel.leading(12*widthScale).size(32*widthScale)
        rankImageV.CenterY == bgView.CenterY
        iconImageV.CenterY == bgView.CenterY
        shadowView.CenterY == bgView.CenterY
        rankLabel.CenterY == bgView.CenterY
        bgView.Leading == iconImageV.Trailing + 12*widthScale
        nameLabel.leading(16*widthScale).trailing(>=150).top(12*widthScale)
        tagLabel.height(15*widthScale)
        tagLabel.Leading == nameLabel.Trailing + 3*widthScale
        tagLabel.CenterY == nameLabel.CenterY
        subLabel.leading(16*widthScale).trailing(60*widthScale)
        subLabel.Top == nameLabel.Bottom
        scoreLabel.leading(16*widthScale).height(16*widthScale)
        scoreLabel.Top == subLabel.Bottom + 2*widthScale
        infoButton.trailing(16*widthScale).height(30*widthScale).width(60*widthScale).centerVertically()
        
        infoButton.addTarget(self, action: #selector(clickInfoButton), for: .touchUpInside)
    }
    
    @objc private func clickInfoButton(){
        
        if let gameID = model?.id {
            yuyueGameBlock?(gameID)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
